package Presentation.action;
import java.awt.Font;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.SwingWorker;
import javax.swing.UIManager;
import javax.swing.plaf.FontUIResource;
import Main.Constants;
import Presentationlayout.AdminLogin;

/**
 * A class that verifies the password from the user. 
 * If nothing is entered or if an invalid password is 
 * entered, a JOptionPane is appearing. Otherwise the
 * user is directed to {@link Admin}.
 * 
 * @author Emma Hägglund
 *
 */

public class LoginSwingWorker extends SwingWorker {
	private AdminLogin login;

	public LoginSwingWorker(AdminLogin login) {
		this.login = login;
	}

	@Override
	protected Object doInBackground() throws Exception {

		char[] pwdFromUser = login.getPwd();

		// The password char is generated into a string
		String pwdString = "";
		for (int i = 0; i < pwdFromUser.length; i++)
			pwdString += pwdFromUser[i];

		// To test if the string is empty or if the password
		// is incorrect
		if (!pwdString.equals("")) {
			if (pwdString.equalsIgnoreCase("jul")) {
				/* TODO Jämföra lösenordet mot databas */
				System.out.println("rätt lösen");
				login.resetPwdField();
				// login.addNewGUIAdmin();
				login.addNewGUIAdmin();

			} else {
				UIManager.put("OptionPane.buttonFont", new FontUIResource(
						new Font(Constants.FONT, Font.PLAIN,
								Constants.FONT_SIZE)));
				JLabel wrongPwd = new JLabel(Constants.LOGIN_WRONG_PWD);
				wrongPwd.setFont(new Font(Constants.FONT, Font.PLAIN,
						Constants.FONT_SIZE));

				JOptionPane.showMessageDialog(null, wrongPwd,
						Constants.LOGIN_FAILED, JOptionPane.ERROR_MESSAGE);
				login.resetPwdField();
				login.getPasswordField().requestFocusInWindow();
			}
		} else {
			UIManager.put("OptionPane.buttonFont", new FontUIResource(new Font(
					Constants.FONT, Font.PLAIN, Constants.FONT_SIZE)));
			JLabel blankPwd = new JLabel(Constants.LOGIN_NO_PWD_ENTERED);
			blankPwd.setFont(new Font(Constants.FONT, Font.PLAIN,
					Constants.FONT_SIZE));
			JOptionPane.showMessageDialog(null, blankPwd,
					Constants.LOGIN_FAILED, JOptionPane.ERROR_MESSAGE);
			login.getPasswordField().requestFocusInWindow();
		}
		return null;
	}
}
